package profile

import (
	"context"
	"fmt"
	"time"

	"usercenter/internal/biz"
	"usercenter/internal/middleware"
	"usercenter/internal/svc"
	"usercenter/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"gorm.io/gorm"
)

type UpdateUserInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserInfoLogic {
	return &UpdateUserInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUserInfoLogic) UpdateUserInfo(req *types.UserInfoUpdateRequest) (*types.UserInfoResponse, error) {
	// 1. 从上下文中获取当前用户ID (需要确保在jwt鉴权中间件中设置了userId)
	currentUserId, ok := l.ctx.Value(middleware.UserIdKey).(int)
	if !ok || currentUserId == 0 {
		return nil, &biz.BizError{
			Code:    401,
			Message: "未授权访问",
		}
	}

	// 2. 查询现有用户信息
	_, err := l.svcCtx.UserModel.FindById(currentUserId)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, &biz.BizError{
				Code:    401,
				Message: "用户不存在",
			}
		}
		l.Logger.Errorf("查询用户信息失败, userId: %d, error: %v", currentUserId, err)
		return nil, &biz.BizError{
			Code:    500,
			Message: "查询用户信息失败",
		}
	}

	// 3. 更新可修改字段
	updateFields := make(map[string]interface{})
	if req.Name != "" {
		updateFields["name"] = req.Name
	}

	// 4. 执行更新操作
	if len(updateFields) > 0 {
		updateFields["updated_at"] = time.Now()
		err = l.svcCtx.UserModel.Update(currentUserId, updateFields)
		if err != nil {
			l.Logger.Errorf("更新用户信息失败, userId: %d, error: %v", currentUserId, err)
			return nil, &biz.BizError{
				Code:    500,
				Message: "更新用户信息失败",
			}
		}

		// 5. 更新成功后删除缓存，下次查询会自动重建缓存
		cacheKey := fmt.Sprintf("%s%d", cacheKeyPrefix, currentUserId)
		if _, err := l.svcCtx.Redis.Del(cacheKey); err != nil && err != redis.Nil {
			l.Logger.Errorf("删除用户缓存失败, key: %s, error: %v", cacheKey, err)
			// 这里不返回错误，因为主要操作已经成功
		}
	}

	// 6. 获取更新后的用户信息
	updatedUser, err := l.svcCtx.UserModel.FindById(currentUserId)
	if err != nil {
		l.Logger.Errorf("获取更新后用户信息失败, userId: %d, error: %v", currentUserId, err)
		return nil, &biz.BizError{
			Code:    500,
			Message: "系统错误，请稍后再试",
		}
	}

	// 7. 异步更新缓存
	// go l.setCache(cacheKeyPrefix, updatedUser)

	return &types.UserInfoResponse{
		Code:    200,
		Message: "更新成功",
		Data: types.UserInfo{
			Id:        currentUserId,
			Email:     updatedUser.Email,
			Name:      updatedUser.Name,
			Avatar:    updatedUser.Avatar,
			CreatedAt: updatedUser.CreatedAt.Format(time.RFC3339),
			UpdatedAt: updatedUser.UpdatedAt.Format(time.RFC3339),
		},
	}, nil
}
